import tkinter as tk
from tkinter import ttk
from datetime import datetime

class EditDialog:
    def __init__(self, parent, trade_data):
        self.dialog = tk.Toplevel(parent)
        self.dialog.title("Edit Trade")
        self.dialog.geometry("600x800")
        self.trade_data = trade_data
        self.result = None
        
        # 创建主框架
        main_frame = ttk.Frame(self.dialog, padding="10")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 创建输入字段
        self.create_input_fields(main_frame)
        
        # 创建按钮
        button_frame = ttk.Frame(main_frame)
        button_frame.grid(row=len(trade_data), column=0, columnspan=2, pady=10)
        
        ttk.Button(button_frame, text="Save", command=self.save).grid(row=0, column=0, padx=5)
        ttk.Button(button_frame, text="Cancel", command=self.cancel).grid(row=0, column=1, padx=5)
        
        # 设置模态
        self.dialog.transient(parent)
        self.dialog.grab_set()
        
    def create_input_fields(self, parent):
        """创建输入字段"""
        row = 0
        self.entries = {}
        
        # 基本信息
        ttk.Label(parent, text="Basic Information", font=('Arial', 12, 'bold')).grid(row=row, column=0, columnspan=2, pady=10)
        row += 1
        
        fields = [
            ('symbol', 'Symbol'),
            ('open_date', 'Open Date'),
            ('open_time', 'Open Time'),
            ('open_price', 'Open Price'),
            ('open_qty', 'Open Quantity'),
            ('close_date', 'Close Date'),
            ('close_time', 'Close Time'),
            ('close_price', 'Close Price'),
            ('close_qty', 'Close Quantity'),
            ('direction', 'Direction'),
            ('trade_type', 'Trade Type'),
            ('order_type', 'Order Type'),
            ('close_order_type', 'Close Order Type')
        ]
        
        for field, label in fields:
            ttk.Label(parent, text=label).grid(row=row, column=0, sticky=tk.W, pady=2)
            self.entries[field] = ttk.Entry(parent, width=40)
            self.entries[field].insert(0, str(self.trade_data[field]))
            self.entries[field].grid(row=row, column=1, sticky=tk.W, pady=2)
            row += 1
        
        # 盈亏信息
        ttk.Label(parent, text="Profit & Loss", font=('Arial', 12, 'bold')).grid(row=row, column=0, columnspan=2, pady=10)
        row += 1
        
        fields = [
            ('gross_profit', 'Gross Profit'),
            ('net_profit', 'Net Profit'),
            ('commission', 'Commission'),
            ('open_commission', 'Open Commission'),
            ('close_commission', 'Close Commission'),
            ('profit_per_lot', 'Profit per Lot'),
            ('point_per_lot', 'Point per Lot'),
            ('total_points', 'Total Points')
        ]
        
        for field, label in fields:
            ttk.Label(parent, text=label).grid(row=row, column=0, sticky=tk.W, pady=2)
            self.entries[field] = ttk.Entry(parent, width=40)
            self.entries[field].insert(0, f"{float(self.trade_data[field]):.2f}")
            self.entries[field].grid(row=row, column=1, sticky=tk.W, pady=2)
            row += 1
        
        # 其他信息
        ttk.Label(parent, text="Other Information", font=('Arial', 12, 'bold')).grid(row=row, column=0, columnspan=2, pady=10)
        row += 1
        
        fields = [
            ('holding_time', 'Holding Time'),
            ('open_session', 'Open Session'),
            ('close_session', 'Close Session'),
            ('session', 'Session'),
            ('nth_trade', 'Nth Trade'),
            ('open_order_id', 'Open Order ID'),
            ('close_order_id', 'Close Order ID')
        ]
        
        for field, label in fields:
            ttk.Label(parent, text=label).grid(row=row, column=0, sticky=tk.W, pady=2)
            self.entries[field] = ttk.Entry(parent, width=40)
            self.entries[field].insert(0, str(self.trade_data[field]))
            self.entries[field].grid(row=row, column=1, sticky=tk.W, pady=2)
            row += 1
    
    def save(self):
        """保存修改"""
        self.result = {}
        for field, entry in self.entries.items():
            value = entry.get()
            # 尝试转换为适当的类型
            try:
                if field in ['open_price', 'close_price', 'gross_profit', 'net_profit', 
                           'commission', 'open_commission', 'close_commission', 
                           'profit_per_lot', 'point_per_lot', 'total_points']:
                    value = float(value)
                elif field in ['open_qty', 'close_qty', 'nth_trade']:
                    value = int(float(value))
            except ValueError:
                pass
            self.result[field] = value
        self.dialog.destroy()
    
    def cancel(self):
        """取消修改"""
        self.dialog.destroy()
    
    def show(self):
        """显示对话框并等待结果"""
        self.dialog.wait_window()
        return self.result 